package org.csu.mypetstore.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
//import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/order")
@SessionAttributes({"order", "orderList","account","cart"})
public class OrderController {

    //KZR完成OrderService后更新
    @Autowired
    public OrderService orderService;
    @Autowired
    public CartService cartService;


    @GetMapping("/newOrderForm")
    public String newOrderForm(HttpSession session,Model model) {

        Account account = (Account)session.getAttribute("account");
        //String userId = account.getUsername();
        //Cart cart = cartService.getCartByUserId(userId);
        //session.setAttribute("cart",cart);
        Cart cart = (Cart)session.getAttribute("cart");

        if (account != null) {
            if(cart != null){
                System.out.println(cart.getNumberOfItems());
                Order order = new Order();
                order.initOrder(account, cart);
                //debug
                List<LineItem> lineItems = order.getLineItems();
                System.out.println(lineItems.size());
                for(int i=0;i<lineItems.size();i++) {
                    System.out.println(lineItems.get(i).getItemId());
                    System.out.println("new order : lineItem.total:" + lineItems.get(i).getTotal());
                }

                model.addAttribute("order", order);
                return "order/NewOrderForm";
            }
            else  return "catalog/view";
              //Cart cart =(Cart)session.getAttribute("cart");
              //session.setAttribute("allOrder", order);
        }
        else {
            return "account/signonForm";
        }
    }
    @PostMapping("/newOrder")
    public String newOrder(Order order, HttpSession session,Model model, String shippingAddressRequired) {
        session.setAttribute("order",order);
        model.addAttribute("order",order);
        if(shippingAddressRequired!=null && shippingAddressRequired.equals("false")) {
            return "order/ShippingForm";
        } else {
            return "order/ConfirmOrder";
        }
    }

    @PostMapping("/confirmOrder")
    public String confirmOrder(Order order,HttpSession session,Model model) {
        orderService.insertOrder(order);
        Cart cart1=(Cart) session.getAttribute("cart");
        List <CartItem> itemLine = cart1.getCartItemList();
        List<BigDecimal>itemCartTocalCost = new ArrayList<>();
        List<LineItem> itemOrderTocalCost = new ArrayList<>();
        for(int i=0;i<itemLine.size();i++){
            itemOrderTocalCost.add(order.getLineItems().get(i));
            itemCartTocalCost.add(itemLine.get(i).getTotal());
            itemOrderTocalCost.get(i).setTotal(itemCartTocalCost.get(i));
        }
        Account a1=(Account)session.getAttribute("account");
        String username = a1.getUsername();
        // 订单已提交，重置购物车
        cartService.deleteCartItemByUsername(username);
        return "order/ViewOrder";
    }

    @GetMapping("/listOrders")
    public String listOrders(@SessionAttribute("account") Account account, Model model) {
        if(account != null) {
            List<Order> orderList = orderService.getOrdersByUsername(account.getUsername());
            model.addAttribute("orderList", orderList);
        }
        return "order/ListOrders";
    }

    @GetMapping("/viewOrder")
    public String viewOrder(String orderId, Model model) {
        if (orderId != null) {
            Order order = orderService.getOrder(Integer.parseInt(orderId));
            model.addAttribute("order", order);
        }
        return "order/ViewOrder";
    }
    //支付成功后到这个url下
    @GetMapping("/viewMyOrder")
    public String viewMyOrder(HttpSession session, Model model){
        Account account = (Account) session.getAttribute("account");
        String username = account.getUsername();
        List<Order> orderList = orderService.getOrdersByUsername(username);
        session.setAttribute("orderList",orderList);
        return  "order/listOrders";
    }

    @PostMapping("/shipping")
    public String shipping(Order order, HttpSession session) {
        Order finalOrder = (Order) session.getAttribute("order");
        finalOrder.setShipAddress1(order.getShipAddress1());
        finalOrder.setShipAddress2(order.getShipAddress2());
        finalOrder.setShipToFirstName(order.getShipToFirstName());
        finalOrder.setShipToLastName(order.getShipToLastName());
        finalOrder.setShipCity(order.getShipCity());
        finalOrder.setShipCountry(order.getShipCountry());
        finalOrder.setShipState(order.getShipState());
        finalOrder.setShipZip(order.getShipZip());

        session.setAttribute("order",finalOrder);
        return "order/ConfirmOrder";
    }
    //管理员查看所有订单
    @GetMapping("/adminAllOrders")
    public String adminAllOrders(Model model){
        List<Order> orderList = orderService.getAllOrders();

        model.addAttribute("orderList",orderList);
        return "admin/ListAllOrders";
    }
    //管理员通过用户名查看某一用户的所有订单
    @GetMapping("/adminListOrders")
    public String adminListOrders(String username,Model model){
        List<Order> orderList = orderService.getOrdersByUsername(username);

        model.addAttribute("orderList",orderList);
        return "admin/ListOrders";

    }
    //管理员通过OrderId查看某一订单
    @GetMapping("/adminViewOrder")
    public String adminViewOrder(String orderId,Model model){
        if(orderId != null){
            Order order = orderService.getOrder(Integer.parseInt(orderId));
            model.addAttribute("order", order);
        }
        return "admin/ViewOrder";

    }


}



